import axios from 'axios'
import { store } from '../store' // 引入vuex
const {
  baseURL,
  EVN,
  productionDomain,
  natDomain,
} = require("../config/global.js")

/*
  md5Data
*/
const md5Data = oldData => {
  let data = JSON.parse(JSON.stringify(oldData || {}))
  data = data || {}
  data.app_key = "titika2020"
  data.timestamp = new Date().getTime()

  // console.log('before', data)
  // data.timestamp = "1584879021029"
  let dateCopy = {} // 临时数据
  let keys = []
  for (let k in data) {
    if (data[k] !== " " && (data[k] === 0 || data[k] === false || data[k])) {
      keys.push(k.toLowerCase())
      dateCopy[k.toLowerCase()] = data[k]
    }
  }
  keys = keys.sort()
  let signStr = ""
  for (let i = 0; i < keys.length; i++) {
    let keyValueStr = ''
    if(typeof dateCopy[keys[i]] === 'object'){
      keyValueStr = JSON.stringify(dateCopy[keys[i]])
      keyValueStr = keyValueStr.replace(/"/g, '\\"')
    }
    else {
      keyValueStr = dateCopy[keys[i]]
    }
    signStr += keys[i].toLowerCase() + keyValueStr
  }
  // data.sign = md5(signStr + "has2f5zbd4")
  //   .toString()
  //   .toUpperCase()
  signStr = signStr + "has2f5zbd4"
  signStr = signStr.replace(/\\"/g, '"')
  let sign = md5(signStr)
  
  data.sign = sign
    .toString()
    .toUpperCase()
  // console.log('after ', data)
  return data
}

/*
  http request
*/
const request = (config, needLogin) => {
  let instance = axios.create({
    baseURL: baseURL[process.env.NODE_ENV],
    async: true,
    crossDomain: true,
    timeout: 10000
  })

  if (config.method == "POST") {
    instance.defaults.headers = {
      "Content-Type": "application/x-www-form-urlencoded"
    }
    // 生成sign
    config.data = config.data ? md5Data(config.data) : undefined
    // post传输时过滤掉值为空和null的属性
    for (const key in config.data) {
      // 过滤键值为空字符串或者null的对象属性
      if (config.data[key] === " " || config.data[key] === null) {
        delete config.data[key]
      }
    }
    // x-www-form-urlencoded 形式传输
    config.data = uRLSearchParams(config.data)
    // config.data = qs.stringify(config.data)
  } else {
    instance.defaults.headers = {}
    // 生成sign
    config.params = config.params ? md5Data(config.params) : undefined
  }

  // 请求拦截器
  instance.interceptors.request.use((config) => {
    config.cancelToken = new axios.CancelToken(function(cancel) {
      store.commit("pushToken", { cancelToken: cancel })
    })
    return config
  })

  // 响应拦截器
  instance.interceptors.response.use(response => {
    if (response.data.ErrorCode) {
      switch (response.data.ErrorCode) {
        case 502:
          if(needLogin !== false){
            initToEntry()
          }
      }
    }
    return response
  })

  // 返回axios
  return instance({
    method: config.method || "GET",
    url: config.url,
    data: config.data,
    params: config.params
  })
}

/*
  跳转到主界面
*/
const initToEntry = () => {
  let shareUserId = getQueryString("shareUserId")
  let shareUserIdStr = shareUserId ? "?shareUserId=" + shareUserId : ""

  setTimeout(() => {
    location.href =
      EVN === "development"
        ? `${natDomain}${shareUserIdStr}#/entry`
        : `${productionDomain}Images/dist/${shareUserIdStr}#/entry`
  }, 1000)
}

/*
  图片加载错误后，填充默认图片
*/
const defaultImg = imgUrl => {
  let img = event.srcElement
  img.src = imgUrl
  img.onerror = null //防止闪图
}

/*
电话格式校验
*/
const phoneReg = str => {
  let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
  return reg.test(str)
}

/*
注册账号格式校验
字母、数字、下划线组成，4-16位
*/
const accountReg = str => {
  let reg = /^[a-zA-z0-9]\w{3,15}$/
  return reg.test(str)
}

/*
密码格式校验
*/
const passwordReg = str => {
  let reg = /^(?=.*[a-zA-Z])(?=.*[1-9]).{8,20}$/
  return reg.test(str)
}

/*
  手机号中间4位星号
*/
const protectPhone = (tel) => {
  var reg = /^(\d{3})\d{4}(\d{4})$/
  tel = tel.replace(reg, "$1****$2")
  return tel
}

/**
 * 银行卡号校验
 * @param {*} cardNum 
 */
const bandCardReg = (cardNum) => {
  var regExp = /^([1-9]{1})(\d{15}|\d{18})$/
  return regExp.test(cardNum) 
}

/**
 * 身份证校验
 * @param {*} cardNum 
 */
function iDCardReg(idcode){
  // 加权因子
  var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
  // 校验码
  var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];

  var code = idcode + "";
  var last = idcode[17];//最后一位

  var seventeen = code.substring(0,17);

  // ISO 7064:1983.MOD 11-2
  // 判断最后一位校验码是否正确
  var arr = seventeen.split("");
  var len = arr.length;
  var num = 0;
  for(var i = 0; i < len; i++){
      num = num + arr[i] * weight_factor[i];
  }
  
  // 获取余数
  var resisue = num%11;
  var last_no = check_code[resisue];

  // 格式的正则
  // 正则思路
  /*
  第一位不可能是0
  第二位到第六位可以是0-9
  第七位到第十位是年份，所以七八位为19或者20
  十一位和十二位是月份，这两位是01-12之间的数值
  十三位和十四位是日期，是从01-31之间的数值
  十五，十六，十七都是数字0-9
  十八位可能是数字0-9，也可能是X
  */
  var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

  // 判断格式是否正确
  var format = idcard_patter.test(idcode);

  // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
  return last === last_no && format ? true : false;
}

/*
  内部函数
  当headers为application/x-www-form-urlencoded时
  转化data参数
*/
function uRLSearchParams(data){
  const paramsObj = new URLSearchParams()
  for (const key in data) {
    // 过滤键值为空字符串或者null的对象属性
    if(data[key] !== ' ' && data[key] !== null){
      if(typeof data[key] === 'object'){
        data[key] = JSON.stringify(data[key])
      }
      paramsObj.append(key, data[key])
    }
  }
  return paramsObj
}

/**
 * 获取浏览器地址参数
 * @param {*} name 需要获取的参数名
 */
const getQueryString = name => {
  var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i")
  let r = window.location.href.substr(1).match(reg)
  if (r != null) return decodeURIComponent(r[2]).split("#")[0]
  return null
}

/**
 * 微信input输入验证码bug去重
 * @param {*} val 验证码
 */
const validateInputSingle = val => {
  let newVal = val
  if (val.length > 9) {
    newVal = val.substr(0, val.length / 2)
  }
  return newVal
}

/**
 * 根据对象里面的属性名,进行对象数组去重
 * @param {*} objarr 
 * @param {*} prop 对象属性名
 */
const distinctObj = (objarr, prop) => {
  let obj = {}
  let newArr = []
  for (let i = 0; i < objarr.length; i++) {
    if (!obj[objarr[i][prop]]) {
      obj[objarr[i][prop]] = 1
      newArr.push(objarr[i])
    }
  }
  return newArr
}

/**
 * 数组去重
 * @param {*} arr 
 */
const distinctArr = (arr) => {
  let obj = {}
  let newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (!obj[arr[i]]) {
      obj[arr[i]] = 1
      newArr.push(arr[i])
    }
  }
  return newArr
}

/**
 * 获取浏览器类型
 */
const getBrowserType = () => {
  let ua = navigator.userAgent.toLowerCase()
  let type = ''
  if(ua.match(/MicroMessenger/i) == "micromessenger"){
    type = 'wechat'
  } else
  if (ua.match(/WeiBo/i) == "weibo") {
    type = "weibo"
  }
  localStorage.setItem("browserType", type)
  return type
}

/**
 * 获取系统类型
 */
const getSystemType = () => {
  let ua = navigator.userAgent
  let isIOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  let isAndroid = ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1
  let type = ''
  if(isIOS){ type = 'ios' }
  if(isAndroid){ type = 'android' }
  return type
}

/**
 * 过滤emoji表情符号
 */
const filterEmoji = str => {
  return str.replace(
    /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g,
    ""
  )
}

/**
 * 是否存在emoji表情符号
 */
const isEmoji = str => {
  let reg = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g
  let result = str.match(reg)
  return result !== null
}

/**
 * 对象转成转译字符串
 */
const convertObjToEscapeStr = (obj) => {
  let str = JSON.stringify(obj)
  str = str.replace(/"/g, '\\"')
  return str
}

/**
 * 根据对象属性值删除数组中的对象
 * @param {*} arr 数组
 * @param {*} attr 属性
 * @param {*} value 属性值
 */
const removeByObjValue = (arr, attr, value) => {
  var index = 0
  for (var i in arr) {
    if (arr[i][attr] == value) {
      index = i
      break
    }
  }
  arr.splice(index, 1)
} 

export {
  md5Data,
  request,
  defaultImg,
  phoneReg,
  accountReg,
  passwordReg,
  protectPhone,
  getQueryString,
  validateInputSingle,
  distinctArr,
  distinctObj,
  getBrowserType,
  getSystemType,
  filterEmoji,
  isEmoji,
  convertObjToEscapeStr,
  removeByObjValue,
  bandCardReg,
  iDCardReg,
}
